package com.rjs.rpc.invoke;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.Socket;

public class ConsumerProxy {

	@SuppressWarnings("unchecked")
	public static <T> T consume(final Class<T> interfaceClass, final String host, final int port) throws Exception {
		return (T)Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class<?>[]{interfaceClass}, new InvocationHandler() {
			public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
				Socket socket = new Socket(host, port);
				ObjectOutputStream output = null;
				ObjectInputStream input = null;
				try {
					output = new ObjectOutputStream(socket.getOutputStream());
					output.writeUTF(method.getName());
					output.writeObject(args);
					input = new ObjectInputStream(socket.getInputStream());
					Object result = input.readObject();
					if (result instanceof Throwable) {
						throw (Throwable)result;
					}
					return result;
				} finally {
					if (input != null) {
						input.close();
					}
					if (output != null) {
						output.close();
					}
					socket.close();
				}
			}
		});
	}
}
